import axios, { AxiosInstance } from "axios";
class AxiosManager{
  static buildDefaultConfig(server:string){
    return {  
      baseURL: "/api",
      timeout: 10000,
      headers:{
      
      "server":server,
      "Content-Type":"application/json"
    }
  }
  }
  static fileAxios= axios.create(this.buildDefaultConfig("fileServer"));
  static mediatorAxios = axios.create(this.buildDefaultConfig("mediatorServer"));
  static adminAxios = axios.create(this.buildDefaultConfig("adminServer"));
  static respondentAxios=axios.create(this.buildDefaultConfig("respondentServer"))
  static applicantAxios=axios.create(this.buildDefaultConfig("applicantServer"))
  static assistantAxios=axios.create(this.buildDefaultConfig("assistantServer"))
  static caseAxios=axios.create(this.buildDefaultConfig("caseServer"))
  static instances:AxiosInstance[]=[
    this.fileAxios,
    this.mediatorAxios,
    this.adminAxios,
    this.respondentAxios,
    this.applicantAxios,
    this.assistantAxios,
    this.caseAxios
  ];
  static interMap:Map<AxiosInstance,Map<string,number>>=new Map();
  
  static addAllInterceptor(name:string,interceptor:Function){
      this.instances.forEach(item=>{
        this.addInterceptor(item,name,interceptor);
      })
    
  }
  private static addInterceptor(instance:AxiosInstance,name:string,interceptor:Function){
    let map=this.interMap.get(instance);
    if(map==null){
      map=new Map();
      this.interMap.set(instance,map);
    }
    if(map.has(name)){
      instance.interceptors.request.eject(map.get(name));
      map.delete(name);
    }
    let id= instance.interceptors.request.use(
      (req)=>interceptor(req)
    );
    map.set(name,id);
  }
}

export default AxiosManager;
